package ar.uade.edu.fain.ad.client.web.servlet.caja.registroPago;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.uade.edu.fain.ad.client.web.servlet.caja.CajaServlet;
import ar.uade.edu.fain.ad.common.exception.FacturaYaPagadaException;
import ar.uade.edu.fain.ad.common.transfer.FacturaVO;
import ar.uade.edu.fain.ad.common.transfer.MedioPagoVO;

/**
 * Servlet implementation class RegistroPagoServlet
 */
public class RegistroPagoServlet extends CajaServlet {

	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegistroPagoServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		final List<MedioPagoVO> medioPagoVOs = getCajaDelegate()
				.buscarMediosPagoHabilitados();
		request.setAttribute("mediosPago", medioPagoVOs);
		forward(getViewBasePath() + "registroPago/registrarPago.jsp", request,
				response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		final Long facturaId = 
				Long.valueOf(request.getParameter("facturaId"));
		final Long medioPagoId = 
				Long.valueOf(request.getParameter("medioPagoId"));
		final FacturaVO facturaVO = new FacturaVO();
		facturaVO.setId(facturaId);
		final MedioPagoVO medioPagoVO = new MedioPagoVO();
		medioPagoVO.setId(medioPagoId);
		try {
			getCajaDelegate().registrarPago(facturaVO, medioPagoVO);
			request.setAttribute("factura", facturaVO);
			forward(getViewBasePath() + "registroPago/pagoRegistrado.jsp",
					request, response);
		} catch (FacturaYaPagadaException e) {
			request.setAttribute("factura", e.getFactura());
			forward(getViewBasePath() + "registroPago/facturaYaPagada.jsp",
					request, response);
		}
	}

}
